package com.jsh.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.vo.*;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.service.accountHead.AccountHeadService;
import com.jsh.erp.service.depot.DepotService;
import com.jsh.erp.service.depotHead.DepotHeadService;
import com.jsh.erp.service.depotItem.DepotItemService;
import com.jsh.erp.service.material.MaterialService;
import com.jsh.erp.service.redis.RedisService;
import com.jsh.erp.service.supplier.SupplierService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.unit.UnitService;
import com.jsh.erp.service.userBusiness.UserBusinessService;
import com.jsh.erp.utils.*;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.jsh.erp.utils.ResponseJsonUtil.returnJson;
import static com.jsh.erp.utils.Tools.getCenternTime;

/**
 * @author ji-sheng-hua 752*718*920
 */
@RestController
@RequestMapping(value = "/depotHead")
@Api(tags = {"单据管理"})
public class DepotHeadController {
    private Logger logger = LoggerFactory.getLogger(DepotHeadController.class);

    @Resource
    private DepotHeadService depotHeadService;

    @Resource
    private AccountHeadService accountHeadService;

    @Resource
    private SupplierService supplierService;

    @Resource
    private DepotService depotService;

    @Resource
    private RedisService redisService;

    @Resource
    private MaterialService materialService;

    @Resource
    private UserBusinessService userBusinessService;
    @Resource
    private DepotItemService depotItemService;

    @Resource
    private UnitService unitService;

    @Resource
    private SystemConfigService systemConfigService;

    /**
     * 批量设置状态-审核或者反审核
     *
     * @param jsonObject
     * @param request
     * @return
     */
    @PostMapping(value = "/batchSetStatus")
    @ApiOperation(value = "批量设置状态-审核或者反审核")
    public String batchSetStatus(@RequestBody JSONObject jsonObject,
                                 HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String status = jsonObject.getString("status");
        String ids = jsonObject.getString("ids");
        int res = depotHeadService.batchSetStatus(status, ids);
        if (res > 0) {
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.ERROR.name : ErpInfo.ERROR.lanCodeName, ErpInfo.ERROR.code);
        }
    }

    @PostMapping(value = "/batchCounterAuditStatus")
    @ApiOperation(value = "批量反审核")
    public String batchCounterAuditStatus(@RequestBody JSONObject jsonObject,
                                 HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String ids = jsonObject.getString("ids");
        int res = depotHeadService.batchCounterAuditStatus(ids);
        if (res > 0) {
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.ERROR.name : ErpInfo.ERROR.lanCodeName, ErpInfo.ERROR.code);
        }
    }

    @PostMapping(value = "/batchEndStatus")
    @ApiOperation(value = "批量强制完成")
    public String batchEndStatus(@RequestBody JSONObject jsonObject,
                                 HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String ids = jsonObject.getString("ids");
        int res = depotHeadService.batchEndStatus(ids);
        if (res > 0) {
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.ERROR.name : ErpInfo.ERROR.lanCodeName, ErpInfo.ERROR.code);
        }
    }

    /**
     * 入库出库明细接口
     *
     * @param currentPage
     * @param pageSize
     * @param oId
     * @param number
     * @param materialParam
     * @param depotId
     * @param beginTime
     * @param endTime
     * @param type
     * @param request
     * @return
     */
    @GetMapping(value = "/findInDetail")
    @ApiOperation(value = "入库出库明细接口")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadVo4InDetail.class)
    })
    public BaseResponseInfo findInDetail(@RequestParam("currentPage") Integer currentPage,
                                         @RequestParam("pageSize") Integer pageSize,
                                         @RequestParam(value = "organId", required = false) String oId,
                                         @RequestParam("number") String number,
                                         @RequestParam("materialParam") String materialParam,
                                         @RequestParam(value = "depotId", required = false) String depotId,
                                         @RequestParam(value = "otherStatus", required = false) String otherStatus,
                                         @RequestParam(value = "categoryId", required = false) String categoryId,
                                         @RequestParam("beginTime") String beginTime,
                                         @RequestParam("endTime") String endTime,
                                         @RequestParam("type") String type,
                                         @RequestParam("remark") String remark,
                                         @RequestParam("subType") String subType,
                                         @RequestParam("creator") String creator,
                                         HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<String> depotList = new ArrayList<>();
            if (!StringUtils.isEmpty(depotId)) {
                depotList.add(depotId);
            } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = depotService.findDepotByCurrentUser();
                for (Object obj : depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getString("id"));
                }
            }
            List<DepotHeadVo4InDetail> resList = new ArrayList<DepotHeadVo4InDetail>();
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            String flag="";
            if (StringUtil.isEmpty(subType)&&"入库".equals(type)){
                flag="期初库存";
            }else if ("期初库存".equals(subType)){
                type=null;
            }
            List<String> idList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = materialService.getListByParentId(categoryId);
            }
            List<DepotHeadVo4InDetail> list = depotHeadService.findByAll(beginTime, endTime, type, materialParam,
                    depotList, oId, number, remark, (currentPage - 1) * pageSize, pageSize,flag,subType,creator,otherStatus,idList);
            int total = depotHeadService.findByAllCount(beginTime, endTime, type, materialParam, depotList, oId, number, remark,flag,subType,creator,otherStatus,idList);
            map.put("total", total);
            //存放数据json数组
            if (null != list) {
                for (DepotHeadVo4InDetail dhd : list) {
                    resList.add(dhd);
                }
            }
            map.put("rows", resList);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 入库出库统计接口
     *
     * @param currentPage
     * @param pageSize
     * @param oId
     * @param materialParam
     * @param depotId
     * @param beginTime
     * @param endTime
     * @param type
     * @param request
     * @return
     */
    @GetMapping(value = "/findInOutMaterialCount")
    @ApiOperation(value = "入库出库统计接口")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadVo4InOutMCount.class)
    })
    public BaseResponseInfo findInOutMaterialCount(@RequestParam("currentPage") Integer currentPage,
                                                   @RequestParam("pageSize") Integer pageSize,
                                                   @RequestParam(value = "organId", required = false) String oId,
                                                   @RequestParam("materialParam") String materialParam,
                                                   @RequestParam(value = "depotId", required = false) String depotId,
                                                   @RequestParam(value = "categoryId", required = false) String categoryId,
                                                   @RequestParam("beginTime") String beginTime,
                                                   @RequestParam("endTime") String endTime,
                                                   @RequestParam("type") String type,
                                                   HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<String> depotList = new ArrayList<>();
            if (!StringUtils.isEmpty(depotId)) {
                depotList.add(depotId);
            } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = depotService.findDepotByCurrentUser();
                for (Object obj : depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getString("id"));
                }
            }
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            String flag="";
            if ("入库".equals(type)){
                flag="期初库存";
            }
            List<String> idList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = materialService.getListByParentId(categoryId);
            }
            List<DepotHeadVo4InOutMCount> list = depotHeadService.findInOutMaterialCount(beginTime, endTime, type, StringUtil.toNull(materialParam),
                    depotList, oId, (currentPage - 1) * pageSize, pageSize,flag,idList);
            int total = depotHeadService.findInOutMaterialCountTotal(beginTime, endTime, type,
                    StringUtil.toNull(materialParam), depotList, oId,flag,idList);
            map.put("total", total);
            map.put("rows", list);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * @Author: wy
     * @Description: 促销统计
     * @DateTime: 2022/8/5 14:57
     * @Params:
     * @Return
     */
    @GetMapping(value = "/findPromotionMaterialCount")
    @ApiOperation(value = "促销统计接口")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadVo4InOutMCount.class)
    })
    public BaseResponseInfo findPromotionMaterialCount(@RequestParam("currentPage") Integer currentPage,
                                                       @RequestParam("pageSize") Integer pageSize,
                                                       @RequestParam(value = "categoryId", required = false) String categoryId,
                                                       @RequestParam("materialParam") String materialParam,
                                                       @RequestParam(value = "depotIds", required = false) String depotIds,
                                                       HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<String> depotList = new ArrayList<>();
            if (!StringUtils.isEmpty(depotIds)) {
                depotList.add(depotIds);
            } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = depotService.findDepotByCurrentUser();
                for (Object obj : depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getString("id"));
                }
            }
            List<String> idList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = materialService.getListByParentId(categoryId);
            }
            List<DepotHeadVo4InOutMCount> list = depotHeadService.findPromotionMaterialCount(StringUtil.toNull(materialParam),
                    depotList, idList, (currentPage - 1) * pageSize, pageSize);
            int total = depotHeadService.findPromotionMaterialCountTotal(StringUtil.toNull(materialParam), depotList, idList);
            map.put("total", total);
            map.put("rows", list);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 调拨明细统计
     *
     * @param currentPage
     * @param pageSize
     * @param number
     * @param materialParam
     * @param depotIdF      调出仓库
     * @param depotId       调入仓库
     * @param beginTime
     * @param endTime
     * @param subType
     * @param request
     * @return
     */
    @GetMapping(value = "/findAllocationDetail")
    @ApiOperation(value = "调拨明细统计")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadVo4InDetail.class)
    })
    public BaseResponseInfo findallocationDetail(@RequestParam("currentPage") Integer currentPage,
                                                 @RequestParam("pageSize") Integer pageSize,
                                                 @RequestParam("number") String number,
                                                 @RequestParam("materialParam") String materialParam,
                                                 @RequestParam(value = "depotId", required = false) String depotId,
                                                 @RequestParam(value = "depotIdF", required = false) String depotIdF,
                                                 @RequestParam(value = "materialId", required = false) String materialId,
                                                 @RequestParam(value = "categoryId", required = false) String categoryId,
                                                 @RequestParam("beginTime") String beginTime,
                                                 @RequestParam("endTime") String endTime,
                                                 @RequestParam("subType") String subType,
                                                 @RequestParam("creator") String creator,
                                                 @RequestParam("remark") String remark,
                                                 HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<String> depotList = new ArrayList<>();
            List<String> depotFList = new ArrayList<>();
            if (!StringUtils.isEmpty(depotId)) {
                depotList.add(depotId);
            } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = depotService.findDepotByCurrentUser();
                for (Object obj : depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getString("id"));
                }
            }
            if (!StringUtils.isEmpty(depotIdF)) {
                depotFList.add(depotIdF);
            } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = depotService.findDepotByCurrentUser();
                for (Object obj : depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotFList.add(object.getString("id"));
                }
            }
            List<String> idList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = materialService.getListByParentId(categoryId);
            }
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            List<DepotHeadVo4InDetail> list = depotHeadService.findAllocationDetail(beginTime, endTime, subType, number, materialParam,
                    depotList, depotFList, remark, (currentPage - 1) * pageSize, pageSize,creator,materialId,idList);
            int total = depotHeadService.findAllocationDetailCount(beginTime, endTime, subType, number, materialParam, depotList, depotFList, remark,creator,materialId,idList);
            map.put("rows", list);
            map.put("total", total);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 对账单接口
     *
     * @param currentPage
     * @param pageSize
     * @param beginTime
     * @param endTime
     * @param organId
     * @param supplierType
     * @param request
     * @return
     */
    @GetMapping(value = "/getStatementAccount")
    @ApiOperation(value = "对账单接口")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadVo4StatementAccount.class)
    })
    public BaseResponseInfo getStatementAccount(@RequestParam("currentPage") Integer currentPage,
                                                @RequestParam("pageSize") Integer pageSize,
                                                @RequestParam("zeroAmount") Integer zeroAmount,
                                                @RequestParam("beginTime") String beginTime,
                                                @RequestParam("endTime") String endTime,
                                                @RequestParam(value = "organId", required = false) String organId,
                                                @RequestParam("supplierType") String supplierType,
                                                HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String type = "";
            String subType = "";
            String type1 = "";
            String subType1 = "";
            String accountType = "";
            if (("供应商").equals(supplierType)) {
                type = "入库";
                type1 = "其它";
                subType = "采购";
                subType1 = "收费确认";
                accountType = "'预付款单','付款','支出','收入'";
            } else if (("客户").equals(supplierType)) {
                type = "出库";
                type1 = "到货";
                subType = "销售";
                subType1 = "厂家到货";
                accountType = "'预收款单','收款','支出','收入'";
            }
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
//            String token = request.getHeader("X-Access-Token");
//            String tenantId = Tools.getTenantIdByToken(token);
            String tenantId = null;
            List<DepotHeadVo4StatementAccount> list = depotHeadService.getStatementAccount(beginTime, endTime, organId,
                    supplierType, type, subType, (currentPage - 1) * pageSize, pageSize, type1, subType1, accountType,zeroAmount,tenantId);
            int total = depotHeadService.getStatementAccountCount(beginTime, endTime, organId,
                    supplierType, type, subType, type1, subType1, accountType,zeroAmount,tenantId);
            for (DepotHeadVo4StatementAccount item : list) {
                BigDecimal preNeed = item.getBeginNeed().add(item.getPreDebtMoney()).subtract(item.getPreBackMoney());
                item.setPreNeed(preNeed);
                BigDecimal allNeedGet = preNeed.add(item.getDebtMoney()).subtract(item.getBackMoney());
                item.setAllNeed(allNeedGet);
            }
            map.put("rows", list);
            map.put("total", total);
            List<DepotHeadVo4StatementAccount> totalPayList = depotHeadService.getStatementAccountTotalPay(beginTime, endTime, organId, supplierType, type, subType, type1, subType1, accountType,tenantId);
            if (totalPayList.size() > 0) {
                DepotHeadVo4StatementAccount totalPayItem = totalPayList.get(0);
                BigDecimal firstMoney = BigDecimal.ZERO;
                BigDecimal lastMoney = BigDecimal.ZERO;
                if (totalPayItem != null) {
                    firstMoney = totalPayItem.getBeginNeed().add(totalPayItem.getPreDebtMoney()).subtract(totalPayItem.getPreBackMoney());
                    lastMoney = firstMoney.add(totalPayItem.getDebtMoney()).subtract(totalPayItem.getBackMoney());
                }
                map.put("firstMoney", firstMoney); //期初
                map.put("lastMoney", lastMoney);  //期末
            }
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 根据编号查询单据信息
     *
     * @param number
     * @param request
     * @return
     */
    @GetMapping(value = "/getDetailByNumber")
    @ApiOperation(value = "根据编号查询单据信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadVo4List.class)
    })
    public BaseResponseInfo getDetailByNumber(@RequestParam("number") String number,
                                              HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        DepotHeadVo4List dhl = new DepotHeadVo4List();
        try {
            List<DepotHeadVo4List> list = depotHeadService.getDetailByNumber(number);
            if (list.size() == 1) {
                dhl = list.get(0);
            }
            res.code = 200;
            res.data = dhl;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }
//
//    @GetMapping(value = "/getHeadByLinkNumber")
//    @ApiOperation(value = "付款单-采购订单下的验收入库和退货单")
//    @ApiResponses({
//            @ApiResponse(code = 200, message = "ok", response = DepotHeadVo4List.class)
//    })
//    public String getHeadByLinkNumber(@RequestParam("number") String number,
//                                                @RequestParam(value = "currentPage",required = false ) Integer currentPage,
//                                                @RequestParam(value="pageSize",required = false) Integer pageSize,
//                                                HttpServletRequest request) throws Exception {
//        Map<String, Object> objectMap = new HashMap<>();
//        String lanCode = redisService.getLanCodeFromSession(request);
//        List<DepotHeadVo4List> list = depotHeadService.getHeadByLinkNumber(number, null, null);
//        if (list != null) {
//            objectMap.put("rows", list);
//            objectMap.put("total", depotHeadService.getHeadByLinkNumber(number,null, null).size());
//            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
//        } else {
//            objectMap.put("rows", new ArrayList<>());
//            objectMap.put("total", 0);
//            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
//        }
//    }

    @GetMapping(value = "/getHeadByLinkNumber")
    @ApiOperation(value = "付款单-采购订单下的验收入库和退货单")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadVo4List.class)
    })
    public BaseResponseInfo getHeadByLinkNumber(@RequestParam("number") String number,
                                                HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            List<DepotHeadVo4List> list = depotHeadService.getHeadByLinkNumber(number);
            res.code = 200;
            res.data = list;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/getInHeadByLinkNumber")
    @ApiOperation(value = "运费单-采购订单下的验收入库")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadVo4List.class)
    })
    public BaseResponseInfo getInHeadByLinkNumber(@RequestParam("number") String number,
                                                HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            List<DepotHeadVo4List> list = depotHeadService.getInHeadByLinkNumber(number);
            res.code = 200;
            res.data = list;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 新增单据主表及单据子表信息
     *
     * @param body
     * @param request
     * @return
     * @throws Exception
     */
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadVo4List.class),
            @ApiResponse(code = 200, message = "ok", response = DepotItemVo4WithInfoEx.class)
    })
    @PostMapping(value = "/addDepotHeadAndDetail")
    @ApiOperation(value = "新增单据主表及单据子表信息")
    public Object addDepotHeadAndDetail(@RequestBody DepotHeadVo4Body body, HttpServletRequest request) throws Exception {
        String lanCode = redisService.getLanCodeFromSession(request);
        JSONObject result = ExceptionConstants.standardSuccess(lanCode);
        String beanJson = body.getInfo();
        String rows = body.getRows();
        String attachment = body.getAttachment();
        Boolean passDirect = body.getPassDirect();
        String functionId = body.getFunctionId();

        depotHeadService.addDepotHeadAndDetail(beanJson, rows, attachment, request, passDirect, functionId);
        return result;
    }

    /**
     * 更新单据主表及单据子表信息
     *
     * @param body
     * @param request
     * @return
     * @throws Exception
     */
    @PutMapping(value = "/updateDepotHeadAndDetail")
    @ApiOperation(value = "更新单据主表及单据子表信息")
    public Object updateDepotHeadAndDetail(@RequestBody DepotHeadVo4Body body, HttpServletRequest request) throws Exception {
        String lanCode = redisService.getLanCodeFromSession(request);
        JSONObject result = ExceptionConstants.standardSuccess(lanCode);
        String beanJson = body.getInfo();
        String rows = body.getRows();
        String attachment = body.getAttachment();
        Boolean passDirect = body.getPassDirect();
        String functionId = body.getFunctionId();
        depotHeadService.updateDepotHeadAndDetail(beanJson, rows, attachment, request, passDirect, functionId);
        return result;
    }

    /**
     * 统计今日采购额、昨日采购额、本月采购额、今年采购额|销售额|零售额
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/getBuyAndSaleStatistics")
    @ApiOperation(value = "统计今日采购额、昨日采购额、本月采购额、今年采购额|销售额|零售额")
    public BaseResponseInfo getBuyAndSaleStatistics(HttpServletRequest request) {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            String today = Tools.getNow() + BusinessConstants.DAY_FIRST_TIME;
            String monthFirstDay = Tools.firstDayOfMonth(Tools.getCurrentMonth()) + BusinessConstants.DAY_FIRST_TIME;
            String yesterdayBegin = Tools.getYesterday() + BusinessConstants.DAY_FIRST_TIME;
            String yesterdayEnd = Tools.getYesterday() + BusinessConstants.DAY_LAST_TIME;
            String yearBegin = Tools.getYearBegin() + BusinessConstants.DAY_FIRST_TIME;
            String yearEnd = Tools.getYearEnd() + BusinessConstants.DAY_LAST_TIME;
            Map<String, Object> map = depotHeadService.getBuyAndSaleStatistics(today, monthFirstDay,
                    yesterdayBegin, yesterdayEnd, yearBegin, yearEnd);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 根据当前用户获取操作员数组，用于控制当前用户的数据权限，限制可以看到的单据范围
     * 注意：该接口提供给部分插件使用，勿删
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/getCreatorByCurrentUser")
    @ApiOperation(value = "根据当前用户获取操作员数组")
    public BaseResponseInfo getCreatorByRoleType(HttpServletRequest request) {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String creator = "";
            String roleType = redisService.getObjectFromSessionByKey(request, "roleType").toString();
            if (StringUtil.isNotEmpty(roleType)) {
                creator = depotHeadService.getCreatorByRoleType(roleType);
            }
            res.code = 200;
            res.data = creator;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 查询存在欠款的单据
     *
     * @param search
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/paymentWarning")
    @ApiOperation(value = "付款预警")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = AccountHeadWIthPaymentWarning.class)
    })
    public String paymentWarning(@RequestParam(value = Constants.SEARCH, required = false) String search,
                                 @RequestParam("currentPage") Integer currentPage,
                                 @RequestParam("pageSize") Integer pageSize,
                                 HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String organId = StringUtil.getInfo(search, "organId");
        String number = StringUtil.getInfo(search, "number");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String status = StringUtil.getInfo(search, "status");
        Integer day = StringUtil.parseInteger(StringUtil.getInfo(search, "day"));
        List<AccountHeadWIthPaymentWarning> list = depotHeadService.paymentWarning(organId, number, beginTime, endTime,status, (currentPage - 1) * pageSize, pageSize, day);
        if (list != null) {
            objectMap.put("rows", list);
            objectMap.put("total", depotHeadService.paymentWarning(organId,  number, beginTime, endTime,status,       null, null, day).size());
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("rows", new ArrayList<>());
            objectMap.put("total", 0);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }

    @GetMapping(value = "/purchaseOrderTracking")
    @ApiOperation(value = "采购订单追踪报表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = AccountHeadWIthTracking.class)
    })
    public String purchaseOrderTracking(@RequestParam(value = Constants.SEARCH, required = false) String search,
                                 @RequestParam("currentPage") Integer currentPage,
                                 @RequestParam("pageSize") Integer pageSize,
                                 HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String organId = StringUtil.getInfo(search, "organId");
        String number = StringUtil.getInfo(search, "number");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String depotId = StringUtil.getInfo(search, "depotId");
        String materialName = StringUtil.getInfo(search, "materialName");
        List<AccountHeadWIthTracking> list = depotHeadService.purchaseOrderTracking(organId, number, beginTime, endTime,depotId, (currentPage - 1) * pageSize, pageSize, materialName);
        if (list != null) {
            objectMap.put("rows", list);
            objectMap.put("total", depotHeadService.purchaseOrderTracking(organId,  number, beginTime, endTime,depotId,       null, null, materialName).size());
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("rows", new ArrayList<>());
            objectMap.put("total", 0);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }
    @GetMapping(value = "/trackingDetailList")
    @ApiOperation(value = "采购订单追踪报表-明细列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadTraceDetail.class)
    })
    public BaseResponseInfo trackingDetailList( @RequestParam(value = "linkNumber") @ApiParam("采购订单编号") String linkNumber,
                                                @RequestParam("type") @ApiParam("类型  其它/出库/入库")String type,
                                                @RequestParam("subType")@ApiParam("出入库类型  采购订单/厂家报价/采购/采购退货") String subType,
                                                @RequestParam("orderType")@ApiParam("1-报损 2-换货") Integer orderType,
                                        HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);

        try {
            List<DepotHeadTraceDetail> list = depotHeadService.trackingDetailList(linkNumber,type, subType,orderType);
            res.code = 200;
            res.data = list;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

//    @GetMapping(value = "/paymentWarning")
//    @ApiOperation(value = "付款预警")
//    @ApiResponses({
//            @ApiResponse(code = 200, message = "ok", response = ShelfLifeWarningVo.class)
//    })
//    public BaseResponseInfo paymentWarning(@RequestParam(defaultValue = "1", required = false) @ApiParam("页码") Integer pageNum,
//                                           @RequestParam(defaultValue = "10", required = false) @ApiParam("显示条数") Integer pageSize,
//                                           @RequestParam(required = false) @ApiParam("天数") Integer day,
//                                           HttpServletRequest request) throws Exception {
//        BaseResponseInfo res = new BaseResponseInfo();
//        Map<String, Object> map = new HashMap<String, Object>();
//        userBusinessService.saveWarning(day, "payment");
//        List<DepotHeadVo4List> vo = depotHeadService.paymentWarning((pageNum - 1) * pageSize, pageSize, day);
//        Integer total = depotHeadService.paymentWarning(null, null, day).size();
//        map.put("rows", vo);
//        map.put("total", total);
//        res.data = map;
//        res.code = 200;
//        return res;
//    }

    @GetMapping(value = "/debtList")
    @ApiOperation(value = "往来详情")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = ReconciliationVoList.class)
    })
    public String debtList(@RequestParam(value = Constants.SEARCH, required = false) String search,
                           @RequestParam("currentPage") Integer currentPage,
                           @RequestParam("pageSize") Integer pageSize,
                           HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String organIdStr = StringUtil.getInfo(search, "organId");
        String organId = organIdStr;
        String materialParam = StringUtil.getInfo(search, "materialParam");
        String number = StringUtil.getInfo(search, "number");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String type = StringUtil.getInfo(search, "type");
        String subType = StringUtil.getInfo(search, "subType");
        String roleType = StringUtil.getInfo(search, "roleType");
        String status = StringUtil.getInfo(search, "status");
        String type1 = StringUtil.getInfo(search, "type1");
        String subType1 = StringUtil.getInfo(search, "subType1");
//        List<DepotHeadVo4List> list = depotHeadService.debtList(organId, materialParam, number, beginTime, endTime, type, subType, roleType, status,type1,subType1,(currentPage - 1) * pageSize, pageSize);
        List<ReconciliationVoList> list = depotHeadService.getAllBillItemByOrganId(organId, beginTime, endTime, (currentPage - 1) * pageSize, pageSize);
        if (list != null) {
            objectMap.put("rows", list);
            objectMap.put("total", depotHeadService.getAllBillItemByOrganIdCount(organId, beginTime, endTime));
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("rows", new ArrayList<>());
            objectMap.put("total", 0);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }
    @GetMapping(value = "/debtOutList")
    @ApiOperation(value = "往来详情")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = ReconciliationVoList.class)
    })
    public String debtOutList(@RequestParam(value = Constants.SEARCH, required = false) String search,
                           @RequestParam("currentPage") Integer currentPage,
                           @RequestParam("pageSize") Integer pageSize,
                           HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String organId = StringUtil.getInfo(search, "organId");
        String materialParam = StringUtil.getInfo(search, "materialParam");
        String number = StringUtil.getInfo(search, "number");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String type = StringUtil.getInfo(search, "type");
        String subType = StringUtil.getInfo(search, "subType");
        String roleType = StringUtil.getInfo(search, "roleType");
        String status = StringUtil.getInfo(search, "status");
        String type1 = StringUtil.getInfo(search, "type1");
        String subType1 = StringUtil.getInfo(search, "subType1");
        List<DepotHeadVo4List> list = depotHeadService.debtList(organId, materialParam, number, beginTime, endTime, type, subType, roleType, status,type1,subType1,(currentPage - 1) * pageSize, pageSize);
//        List<ReconciliationVoList> list = depotHeadService.getAllBillItemByOrganId(organId, beginTime, endTime, (currentPage - 1) * pageSize, pageSize);
        if (list != null) {
            objectMap.put("rows", list);
            objectMap.put("total", depotHeadService.getAllBillItemByOrganIdCount(organId, beginTime, endTime));
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("rows", new ArrayList<>());
            objectMap.put("total", 0);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }


    @GetMapping(value = "/requireGoods")
    @ApiOperation(value = "要货申请进度表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = RequireGoodsVo.class)
    })
    public BaseResponseInfo requireGoods(@RequestParam(value = "status", required = false) @ApiParam("状态(0:未完成 1:已完成)") String status,
                                         @RequestParam(defaultValue = "1", required = false) @ApiParam("页码") Integer pageNum,
                                         @RequestParam(defaultValue = "10", required = false) @ApiParam("显示条数") Integer pageSize,
                                         HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        List<RequireGoodsVo> vo = depotHeadService.requireGoods(status, (pageNum - 1) * pageSize, pageSize);
        Integer total = depotHeadService.requireGoods(status, null, null).size();
        map.put("rows", vo);
        map.put("total", total);
        res.data = map;
        res.code = 200;
        return res;
    }

    @GetMapping(value = "/requireGoodsDetails")
    @ApiOperation(value = "要货申请进度表详情")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = RequireDetailsVo.class)
    })
    public BaseResponseInfo requireGoodsDetails(@RequestParam(value = "defaultNumber", required = false) @ApiParam("票据号") String defaultNumber,
                                                HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        List<RequireDetailsVo> vo = depotHeadService.requireGoodsDetails(defaultNumber);
        map.put("rows", vo);
        res.code = 200;
        res.data = map;
        return res;
    }

    @GetMapping(value = "/factoryOutLet")
    @ApiOperation(value = "厂家直发进度")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = FactoryOutLetVo.class)
    })
    public BaseResponseInfo factoryOutLet(@RequestParam(value = "beginTime", required = false) @ApiParam("开始时间")  String beginTime,
                                          @RequestParam(value = "endTime", required = false) @ApiParam("结束时间")  String endTime,
                                          @RequestParam(value = "number", required = false) @ApiParam("厂家直发订单")  String number,
                                          @RequestParam(value = "organId", required = false) @ApiParam("客户id")  String organId,
                                          @RequestParam(defaultValue = "1", required = false) @ApiParam("页码") Integer pageNum,
                                          @RequestParam(defaultValue = "10", required = false) @ApiParam("显示条数") Integer pageSize,
                                          HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        List<FactoryOutLetVo> vo = depotHeadService.factoryOutLet(beginTime,endTime,number,organId, (pageNum - 1) * pageSize, pageSize);
        Integer total = depotHeadService.factoryOutLet(beginTime,endTime,number,organId, null, null).size();
        map.put("rows", vo);
        map.put("total", total);
        res.data = map;
        res.code = 200;
        return res;
    }

    @GetMapping(value = "/factoryOutLetDetails")
    @ApiOperation(value = "厂家直发订单追踪报表-明细列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadTraceDetail.class)
    })
    public BaseResponseInfo factoryOutLetDetails( @RequestParam(value = "linkNumber") @ApiParam("厂家直发编号") String linkNumber,
                                                @RequestParam("type") @ApiParam("类型  其它/到货/")String type,
                                                @RequestParam("subType")@ApiParam("出入库类型") String subType,
                                                @RequestParam("orderType")@ApiParam("1-报损 2-换货") Integer orderType,
                                                HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);

        try {
            List<DepotHeadTraceDetail> list = depotHeadService.factoryOutLetDetails(linkNumber,type, subType,orderType);
            res.code = 200;
            res.data = list;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

//    @GetMapping(value = "/factoryOutLetDetails")
//    @ApiOperation(value = "厂家直发进度详情")
//    @ApiResponses({
//            @ApiResponse(code = 200, message = "ok", response = FactoryOutLetDetailVo.class)
//    })
//    public BaseResponseInfo factoryOutLetDetails(@RequestParam(value = "headerId", required = false) @ApiParam("主表id") String headerId,
//                                                 HttpServletRequest request) throws Exception {
//        BaseResponseInfo res = new BaseResponseInfo();
//        Map<String, Object> map = new HashMap<String, Object>();
//        List<FactoryOutLetDetailVo> vo = depotHeadService.factoryOutLetDetails(headerId);
//        map.put("rows", vo);
//        res.code = 200;
//        res.data = map;
//        return res;
//    }

    /**
     * @Author: wy
     * @Description: 智能补货
     * @DateTime: 2022/8/5 16:01
     * @Params:
     * @Return
     */
    @PostMapping(value = "/replenishment")
    @ApiOperation(value = "智能补货")
    public Object replenishment(@RequestBody JSONObject jsonObject,
                                HttpServletRequest request) throws Exception {
        String lanCode = redisService.getLanCodeFromSession(request);
        JSONObject result = ExceptionConstants.standardSuccess(lanCode);
        Boolean passDirect = jsonObject.getBoolean("passDirect");
//        String ids = jsonObject.getString("ids");
        Integer day = jsonObject.getInteger("day");
        String functionId = jsonObject.getString("functionId");
        String replenishment = jsonObject.getString("replenishment");
        List<Replenishment> replenishmentList = JSONObject.parseArray(replenishment, Replenishment.class);
        if (replenishmentList.size() > 0) {
            for (Replenishment r : replenishmentList) {
                String organId = materialService.getOrganIdByMaterialId(r.getId());
                if (StringUtils.isEmpty(organId)) {
                    StringBuilder stringBuilder = materialService.notIdList(r.getId());
                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_NOT_DEFAULT_SUPPLIER_CODE
                            , String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_NOT_DEFAULT_SUPPLIER_MSG : ExceptionConstants.MATERIAL_NOT_DEFAULT_SUPPLIER_MSG_US, stringBuilder.toString()));
                } else {
                    r.setOrganId(organId);
                }
            }
        }
        Map<String, List<Replenishment>> map = replenishmentList.stream().collect(Collectors.groupingBy(Replenishment::getOrganId));
        Set<String> organIds = map.keySet();
        for (String organId : organIds) {
            List<Replenishment> replenishments = map.get(organId);
            depotHeadService.replenishment(replenishments, organId, passDirect, functionId, request, day);
        }
//        for (List<Replenishment> list:map.values()){
//            depotHeadService.replenishment(list, passDirect, functionId, request, day);
//        }
//        depotHeadService.replenishment(map.values(), replica.getIds(), passDirect, functionId, request,  day,depotId);
//        List<Replenishment> list = materialService.getOrganIdByMaterialId(idList);
//        List<Replenishment> list = materialService.getOrganIdByMaterialId(replenishmentList);
//        for (Replenishment replica : list) {
//            if (StringUtil.isEmpty(replica.getOrganId())) {
//                List<String> notIdList = StringUtil.strToStringList(replica.getIds());
//                StringBuilder stringBuilder = materialService.notIdList(notIdList);
//                throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_NOT_DEFAULT_SUPPLIER_CODE
//                        , String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_NOT_DEFAULT_SUPPLIER_MSG : ExceptionConstants.MATERIAL_NOT_DEFAULT_SUPPLIER_MSG_US, stringBuilder.toString()));
//            }
//            depotHeadService.replenishment(replica.getOrganId(), replica.getIds(), passDirect, functionId, request,  day,depotId);
//        }
        return result;
    }

    @GetMapping(value = "/purchaseAlert")
    @ApiOperation(value = "采购订单预警")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadVo4List.class)
    })
    public BaseResponseInfo purchaseAlert(@RequestParam(defaultValue = "1", required = false) @ApiParam("页码") Integer pageNum,
                                          @RequestParam(defaultValue = "10", required = false) @ApiParam("显示条数") Integer pageSize,
                                          @RequestParam @ApiParam("天数") Integer day,
                                          HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        day = userBusinessService.saveWarning(day, "purchase");
        List<DepotHeadVo4List> vo = depotHeadService.purchaseAlert((pageNum - 1) * pageSize, pageSize, day);
        Integer total = depotHeadService.purchaseAlert(null, null, day).size();
        map.put("rows", vo);
        map.put("total", total);
        res.data = map;
        res.code = 200;
        return res;
    }

    @GetMapping(value = "/manufacturerWarning")
    @ApiOperation(value = "厂家直发预警")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadVo4List.class)
    })
    public BaseResponseInfo manufacturerWarning(@RequestParam(defaultValue = "1", required = false) @ApiParam("页码") Integer pageNum,
                                                @RequestParam(defaultValue = "10", required = false) @ApiParam("显示条数") Integer pageSize,
                                                @RequestParam(required = false) @ApiParam("天数") Integer day,
                                                HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        day = userBusinessService.saveWarning(day, "factor");
        List<DepotHeadVo4List> vo = depotHeadService.manufacturerWarning((pageNum - 1) * pageSize, pageSize, day);
        Integer total = depotHeadService.manufacturerWarning(null, null, day).size();
        map.put("rows", vo);
        map.put("total", total);
        res.data = map;
        res.code = 200;
        return res;
    }

    @GetMapping(value = "/purchaseApplicationAlert")
    @ApiOperation(value = "要货申请预警")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadVo4List.class)
    })
    public BaseResponseInfo purchaseApplicationAlert(@RequestParam(defaultValue = "1", required = false) @ApiParam("页码") Integer pageNum,
                                                     @RequestParam(defaultValue = "10", required = false) @ApiParam("显示条数") Integer pageSize,
                                                     @RequestParam(required = false) @ApiParam("天数") Integer day,
                                                     HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        day = userBusinessService.saveWarning(day, "apply");
        List<DepotHeadVo4List> vo = depotHeadService.purchaseApplicationAlert((pageNum - 1) * pageSize, pageSize, day);
        Integer total = depotHeadService.purchaseApplicationAlert(null, null, day).size();
        map.put("rows", vo);
        map.put("total", total);
        res.data = map;
        res.code = 200;
        return res;
    }

    @GetMapping(value = "/shelfLifeWarning")
    @ApiOperation(value = "保质期预警")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = ShelfLifeWarningVo.class)
    })
    public BaseResponseInfo shelfLifeWarning(@RequestParam(defaultValue = "1", required = false) @ApiParam("页码") Integer pageNum,
                                             @RequestParam(defaultValue = "10", required = false) @ApiParam("显示条数") Integer pageSize,
                                             @RequestParam(required = false) @ApiParam("天数") Integer day,
                                             HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        userBusinessService.saveWarning(day, "exp");
        String token = request.getHeader("X-Access-Token");
        String tenantId = Tools.getTenantIdByToken(token);

        List<ShelfLifeWarningVo> vo = depotHeadService.shelfLifeWarning((pageNum - 1) * pageSize, pageSize, tenantId);
        Integer total = depotHeadService.shelfLifeWarning(null, null, tenantId).size();
        map.put("rows", vo);
        map.put("total", total);
        res.data = map;
        res.code = 200;
        return res;
    }


    @PostMapping(value = "/addRetailOrder")
    @ApiOperation(value = "添加零售单")
    public Object addRetailOrder(@RequestBody JSONObject jsonObject,
                                 HttpServletRequest request) throws Exception {
        List<AddRetailOrderVo> list = JSONObject.parseArray(jsonObject.getString("goods_info"), AddRetailOrderVo.class);
        String equipmentNo = jsonObject.getString("equipmentNo");
        return depotHeadService.addRetailOrder(list, request,equipmentNo);
    }

    @PostMapping(value = "/addSaleRetailOrder")
    @ApiOperation(value = "添加销售零售单")
    public Object addSaleRetailOrder(@RequestBody JSONObject jsonObject,
                                 HttpServletRequest request) throws Exception {
        List<AddRetailOrderVo> list = JSONObject.parseArray(jsonObject.getString("goods_info"), AddRetailOrderVo.class);
        String remark = jsonObject.getString("remark");
        String equipmentNo = jsonObject.getString("equipmentNo");
        return depotHeadService.addSaleRetailOrder(list,request,remark,equipmentNo);
    }

    @PostMapping(value = "/getShoppingRunningWaterTotal")
    @ApiOperation(value = "零售统计")
    public Map getShoppingRunningWaterTotal(@RequestBody JSONObject jsonObject,
                                            HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String orderNumber = jsonObject.getString("order_number");
        String startTime = jsonObject.getString("start_time");
        String endTime = jsonObject.getString("end_time");
        BigDecimal x_money = depotItemService.getShoppingRunningWaterTotal("出库", "零售", startTime, endTime, orderNumber);
        BigDecimal r_money = depotItemService.getShoppingRunningWaterTotal("入库", "零售退货", startTime, endTime, orderNumber);
        map.put("h_money", 0);
        map.put("mec_money", 0);
        map.put("o_money", 0);
        map.put("r_money", r_money);
        map.put("w_money", 0);
        map.put("x_money", x_money);
        map.put("z_money", 0);
        return map;
    }

    @PostMapping(value = "/getShoppingRunningWater")
    @ApiOperation(value = "零售明细")
    public Map getShoppingRunningWater(@RequestBody JSONObject jsonObject,
                                       HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> depotList = new ArrayList<>();
        //未选择仓库时默认为当前用户有权限的仓库
        JSONArray depotArr = depotService.findDepotByCurrentUser();
        for (Object obj : depotArr) {
            JSONObject object = JSONObject.parseObject(obj.toString());
            depotList.add(object.getString("id"));
        }

        String orderNumber = jsonObject.getString("order_number");
        Integer page = jsonObject.getInteger("page");
        Integer num = jsonObject.getInteger("num");
        String startTime = jsonObject.getString("start_time");
        String endTime = jsonObject.getString("end_time");

        List<Map<String, Object>> mapList = depotHeadService.getShoppingRunningWater(startTime, endTime,
                depotList, (page - 1) * num, num, orderNumber);
        int total = depotHeadService.getShoppingRunningWaterCount(startTime, endTime, depotList, orderNumber);

        map.put("count", total);
        map.put("order", mapList);
        map.put("status", 1);
        return map;
    }

    @PostMapping(value = "/getSaleShoppingRunningWater")
    @ApiOperation(value = "仓库零售明细")
    public Map getSaleShoppingRunningWater(@RequestBody JSONObject jsonObject,
                                       HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> depotList = new ArrayList<>();
        //未选择仓库时默认为当前用户有权限的仓库
        JSONArray depotArr = depotService.findDepotByCurrentUser();
        for (Object obj : depotArr) {
            JSONObject object = JSONObject.parseObject(obj.toString());
            depotList.add(object.getString("id"));
        }

        String orderNumber = jsonObject.getString("order_number");
        Integer page = jsonObject.getInteger("page");
        Integer num = jsonObject.getInteger("num");
        String startTime = jsonObject.getString("start_time");
        String endTime = jsonObject.getString("end_time");

        List<Map<String, Object>> mapList = depotHeadService.getSaleShoppingRunningWater(startTime, endTime,
                depotList, (page - 1) * num, num, orderNumber);
        int total = depotHeadService.getSaleShoppingRunningWaterCount(startTime, endTime, depotList, orderNumber);

        map.put("count", total);
        map.put("order", mapList);
        map.put("status", 1);
        return map;
    }


    @PostMapping(value = "/searchOrder_v1")
    @ApiOperation(value = "零售退款列表")
    public Map<String, Object> searchOrder_v1(@RequestBody JSONObject jsonObject,
                                              HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String order_no = jsonObject.getString("order_no");
        if (StringUtils.isEmpty(order_no)) {
            map.put("status", 0);
            map.put("msg", "zh".equals(systemConfigService.getLanCode()) ? "缺少参数" : "Missing parameters");
            return map;
        }
        return depotHeadService.searchOrder_v1(order_no);
    }

    @PostMapping(value = "/updateRetailOrder")
    @ApiOperation(value = "修改零售单")
    public Object updateRetailOrder(@RequestParam String order_no, @RequestParam String pay_type,
                                    @RequestParam BigDecimal amount_received, @RequestParam BigDecimal all_money,
                                    @RequestParam BigDecimal pay_money,  @RequestParam String accountMoneyList,@RequestParam String accountIdList,
                                    @RequestParam String accountId,
                                    HttpServletRequest request) throws Exception {
        return depotHeadService.updateRetailOrder(order_no, amount_received, all_money, request,accountMoneyList,accountIdList,accountId);
    }

    @PostMapping(value = "/addSearchOrder")
    @ApiOperation(value = "添加零售单退款")
    public Object addSearchOrder(@RequestBody JSONObject jsonObject,
                                 HttpServletRequest request) throws Exception {
        return depotHeadService.addSearchOrder(jsonObject, request);
    }

    @PostMapping(value = "/uploadOffpayOrder")
    @ApiOperation(value = "上传离线订单")
    public Object uploadOffpayOrder(@RequestBody JSONObject jsonObject,
                                    HttpServletRequest request) throws Exception {
        return depotHeadService.uploadOffpayOrder(jsonObject, request);
    }

    @GetMapping(value = "getIssuePurchase")
    @ApiOperation(value = "下达采购按钮列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotItemVo4WithInfoEx.class)
    })
    public BaseResponseInfo getIssuePurchase(@RequestParam("headerId") String headerId,
                                             HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            List<DepotItemVo4WithInfoEx> dataList = new ArrayList<DepotItemVo4WithInfoEx>();
            if (!StringUtil.isEmpty(headerId)) {
                dataList = depotItemService.getDetailList(headerId);
            }
            DepotHead depotHead = depotHeadService.getDepotHeadById(headerId);
            JSONObject outer = new JSONObject();
            outer.put("total", dataList.size());
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (dataList.size() > 0) {
//                Map<String,BigDecimal> currentStockMap = materialService.getCurrentStockMapByMaterialList(dataList,null);
                for (DepotItemVo4WithInfoEx diEx : dataList) {
                    JSONObject item = new JSONObject();
                    item.put("id", diEx.getId());
                    item.put("headerId", headerId);
                    item.put("materialExtendId", diEx.getMaterialExtendId() == null ? "" : diEx.getMaterialExtendId());
                    item.put("barCode", diEx.getBarCode());
                    item.put("name", diEx.getMName());
                    item.put("standard", diEx.getMStandard());
                    item.put("model", diEx.getMModel());
                    item.put("color", diEx.getMColor());
                    BigDecimal stock = materialService.getCurrentStockMapByMaterialId(diEx.getMaterialId(),diEx.getDepotId());
                    item.put("stock", stock);
                    item.put("unit", diEx.getMaterialUnit());
                    item.put("snList", diEx.getSnList());
                    item.put("batchNumber", diEx.getBatchNumber());
                    item.put("expirationDate", Tools.parseDateToStr(diEx.getExpirationDate()));
                    item.put("sku", diEx.getSku());
                    item.put("enableSerialNumber", diEx.getEnableSerialNumber());
                    item.put("enableBatchNumber", diEx.getEnableBatchNumber());
                    item.put("operNumber", diEx.getOperNumber());
                    item.put("basicNumber", diEx.getBasicNumber());
                    item.put("preNumber", diEx.getOperNumber()); //原数量
//                    //是否有对当前供应商的采购记录 有-取最近一条当前商品的单价
//                    BigDecimal recentPurchase = depotItemService.getItemByHeaderIdAndBarcode(diEx.getMaterialId(), diEx.getOrganId(),diEx.getMaterialExtendId());
//                    if (null !=recentPurchase && recentPurchase.compareTo(BigDecimal.ZERO)>0){
//                        item.put("billPrice", recentPurchase);
//                        item.put("allPrice", recentPurchase.multiply(diEx.getOperNumber()));
////                        item.put("taxUnitPrice",recentPurchase.multiply(diEx.getOperNumber()));
////                        item.put("taxLastMoney",recentPurchase.multiply(diEx.getOperNumber()));
//                    }else {
//                        //采购价
//                        item.put("billPrice", diEx.getPurchaseDecimal());
//                        item.put("allPrice", diEx.getPurchaseDecimal().multiply(diEx.getOperNumber()));
////                        item.put("taxUnitPrice",diEx.getPurchaseDecimal().multiply(diEx.getOperNumber()));
////                        item.put("taxLastMoney",diEx.getPurchaseDecimal().multiply(diEx.getOperNumber()));
//                    }
                    //采购价
                    if ("赠品".equals(diEx.getPriceNote()) || "gift".equals(diEx.getPriceNote())){
                        item.put("billPrice", 0);
                        item.put("allPrice", 0);
                    }else {
                        item.put("billPrice", diEx.getPurchaseDecimal());
                        item.put("allPrice", diEx.getPurchaseDecimal().multiply(diEx.getOperNumber()));
                    }
                    item.put("taxUnitPrice", "");
                    item.put("remark", diEx.getRemark());
                    item.put("linkId", diEx.getLinkId());
                    item.put("depotId", diEx.getDepotId() == null ? "" : diEx.getDepotId());
                    item.put("depotName", diEx.getDepotId() == null ? "" : diEx.getDepotName());
                    item.put("anotherDepotId", diEx.getAnotherDepotId() == null ? "" : diEx.getAnotherDepotId());
                    item.put("anotherDepotName", diEx.getAnotherDepotId() == null ? "" : diEx.getAnotherDepotName());
                    item.put("taxRate", diEx.getTaxRate());
                    item.put("taxMoney", "");
                    item.put("taxLastMoney", "");
                    item.put("mType", diEx.getMaterialType());
                    item.put("priceNote", diEx.getPriceNote());
                    item.put("organId", diEx.getOrganId());
                    item.put("organName", diEx.getOrganName());
                    item.put("op", 1);
                    if (depotHead.getArrivalTime() != null) {
                        item.put("arrivalTime", getCenternTime(depotHead.getArrivalTime()));
                    }
                    item.put("deliveryMethod", depotHead.getDeliveryMethod());
                    //采购订单原数量
                    item.put("custom6", diEx.getCustom6());
                    //采购订单原含税单价
                    item.put("custom7", diEx.getCustom7());
                    item.put("custom1",diEx.getCustom1());
                    item.put("custom2",diEx.getCustom2());
                    item.put("custom3",diEx.getCustom3());
                    item.put("sourceId",diEx.getCustom4());
                    item.put("custom4",diEx.getCustom4());
                    item.put("custom5",diEx.getCustom5());
                    item.put("custom12",diEx.getCustom12());
                    dataArray.add(item);
                }
            }

            outer.put("rows", dataArray);
            res.code = 200;
            res.data = outer;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @PostMapping(value = "issuePurchase")
    @ApiOperation(value = "下达采购按钮")
    public BaseResponseInfo issuePurchase(@RequestBody DepotHeadVo4Body body,
                                          HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        String id = body.getId();
        String rows = body.getRows();
        Boolean passDirect = body.getPassDirect();
        String functionId = body.getFunctionId();
        DepotHead depotHead = depotHeadService.getDepotHeadByIds(id);
        int i = depotHeadService.issuePurchase(depotHead, rows, passDirect, functionId, request);
        res.code = 200;
        res.data = "zh".equals(lanCode) ? "成功生成" + i + "条下达采购订单" : i + "purchase order was successfully generated";
        return res;
    }

    @GetMapping(value = "/getDepotHeadByOrganId")
    @ApiOperation(value = "根据客户/供应商ID查询单据信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHead.class)
    })
    public BaseResponseInfo getDepotHeadByOrganId(@RequestParam("organId") String organId,
                                                  HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            List<DepotHead> list = depotHeadService.getDepotHeadByOrganId(organId);
            res.code = 200;
            res.data = list;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "acceptableQuantity")
    @ApiOperation(value = "可验收数")
    public BaseResponseInfo acceptableQuantity(@RequestParam("id") String id, @RequestParam("materialId") String materialId,
                                               HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        BigDecimal data = depotHeadService.acceptableQuantity(id, materialId);
        res.code = 200;
        res.data = data;


        return res;
    }

    @PostMapping(value = "/generatorStockTake")
    @ApiOperation(value = "盘点生单")
    public Object generatorStockTake(@RequestBody JSONObject jsonObject,
                                     HttpServletRequest request) throws Exception {
        String lanCode = redisService.getLanCodeFromSession(request);
        JSONObject result = ExceptionConstants.standardSuccess(lanCode);
        Boolean passDirect = jsonObject.getBoolean("passDirect");
//        String functionVo = jsonObject.getString("functionVo");
//        List<FunctionVoList> functionVoList = JSONObject.parseArray(functionVo, FunctionVoList.class);
        String id = jsonObject.getString("id");
        depotHeadService.generatorStockTake(id, passDirect,  request);
        return result;
    }

//    @GetMapping(value = "/receiptPrinters")
//    @ApiOperation(value = "打印小票信息")
//    public BaseResponseInfo receiptPrinters(@RequestParam("id") String id,
//                                     HttpServletRequest request) throws Exception {
//        BaseResponseInfo res = new BaseResponseInfo();
//        BigDecimal data = depotHeadService.receiptPrinters(id);
//        res.code = 200;
//        res.data = data;
//        return res;
//    }

    /**
     * @Author: wy
     * @Description: 促销统计
     * @DateTime: 2022/8/5 14:57
     * @Params:
     * @Return
     */
    @GetMapping(value = "/findPromotionCreatorCount")
    @ApiOperation(value = "职员销售统计")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadWithStaffSales.class)
    })
    public BaseResponseInfo findPromotionCreatorCount(@RequestParam("currentPage") Integer currentPage,
                                                       @RequestParam("pageSize") Integer pageSize,
                                                       @RequestParam(value = "creator",required = false) String creator,
                                                       @RequestParam(value = "organId",required = false) String organId,
                                                       @RequestParam("beginTime") String beginTime,
                                                       @RequestParam("endTime") String endTime,
                                                       HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
            List<DepotHeadWithStaffSales> list = depotHeadService.findPromotionCreatorCount(StringUtil.toNull(creator),
                    beginTime, endTime, (currentPage - 1) * pageSize, pageSize,organId);
            int total = depotHeadService.findPromotionCreatorCountTotal(StringUtil.toNull(creator), beginTime, endTime,organId);
            map.put("total", total);
            map.put("rows", list);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/findDepotByCreatorDetail")
    @ApiOperation(value = "职员销售统计明细")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadWithStaffSalesDetail.class)
    })
    public BaseResponseInfo findDepotByCreatorDetail(@RequestParam("currentPage") Integer currentPage,
                                                      @RequestParam("pageSize") Integer pageSize,
                                                      @RequestParam(value = "creator",required = false) String creator,
                                                      @RequestParam(value = "organId",required = false) String organId,
                                                      @RequestParam("beginTime") String beginTime,
                                                      @RequestParam("endTime") String endTime,
                                                      HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
            List<DepotHeadWithStaffSalesDetail> list = depotHeadService.findDepotByCreatorDetail(StringUtil.toNull(creator),
                    beginTime, endTime, (currentPage - 1) * pageSize, pageSize,organId);
            int total = depotHeadService.findDepotByCreatorDetailTotal(StringUtil.toNull(creator), beginTime, endTime,organId);
            map.put("total", total);
            map.put("rows", list);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/findRebate")
    @ApiOperation(value = "返利统计")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadWithRebate.class)
    })
    public BaseResponseInfo findRebate(@RequestParam("creator") String creator,
                                        @RequestParam("organId") String organId,
                                        @RequestParam("number") String number,
                                        @RequestParam("custom12") Integer custom12,
                                        @RequestParam("beginTime") String beginTime,
                                        @RequestParam("endTime") String endTime,
                                       @RequestParam("currentPage") Integer currentPage,
                                       @RequestParam("pageSize") Integer pageSize,
                                                      HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);
            List<DepotHeadWithRebate> list = depotHeadService.findRebate(StringUtil.toNull(creator),
                    StringUtil.toNull(organId),StringUtil.toNull(number),custom12,beginTime, endTime, (currentPage - 1) * pageSize, pageSize);
            int total = depotHeadService.findRebateTotal(StringUtil.toNull(creator),
                    StringUtil.toNull(organId),StringUtil.toNull(number),custom12, beginTime, endTime);
            map.put("total", total);
            map.put("rows", list);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/paySalesOrderList")
    @ApiOperation(value = "获取信息列表")
    public String paySalesOrderList(@RequestParam(value = Constants.PAGE_SIZE, required = false) Integer pageSize,
                          @RequestParam(value = Constants.CURRENT_PAGE, required = false) Integer currentPage,
                          @RequestParam(value = Constants.SEARCH, required = false) String search,
                          HttpServletRequest request)throws Exception {
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> objectMap = new HashMap<String, Object>();

        String type = StringUtil.getInfo(search, "type");
        String subType = StringUtil.getInfo(search, "subType");
        String status = StringUtil.getInfo(search, "status");
        String number = StringUtil.getInfo(search, "number");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String materialParam = StringUtil.getInfo(search, "materialParam");
        List<DepotHeadVo4List> list = depotHeadService.selectSalesOrderByConditionDepotHead(type,subType,status, number,
                beginTime, endTime, materialParam,(currentPage - 1) * pageSize, pageSize);
        if (list != null) {
            objectMap.put("total", depotHeadService.countsSalesOrderByDepotHead(type,subType,status, number,
                    beginTime, endTime, materialParam));
            objectMap.put("rows", list);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("total", BusinessConstants.DEFAULT_LIST_NULL_NUMBER);
            objectMap.put("rows", new ArrayList<Object>());
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }
    @GetMapping(value = "/getSalesHeadByLinkNumber")
    @ApiOperation(value = "收款单-销售订单下的销售和退货单")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadVo4List.class)
    })
    public BaseResponseInfo getSalesHeadByLinkNumber(@RequestParam("number") String number,
                                                HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            List<DepotHeadVo4List> list = depotHeadService.getSalesHeadByLinkNumber(number);
            res.code = 200;
            res.data = list;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/findPromotionMaterialDetail")
    @ApiOperation(value = "促销明细报表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadWithItem.class)
    })
    public BaseResponseInfo findPromotionMaterialDetail(@RequestParam("currentPage") Integer currentPage,
                                                        @RequestParam("pageSize") Integer pageSize,
                                                        @RequestParam(value = "organId", required = false) String oId,
                                                        @RequestParam("number") String number,
                                                        @RequestParam("materialParam") String materialParam,
                                                        @RequestParam(value = "depotId", required = false) String depotId,
                                                        @RequestParam(value = "categoryId", required = false) String categoryId,
                                                        @RequestParam("beginTime") String beginTime,
                                                        @RequestParam("endTime") String endTime,
                                                        @RequestParam("type") String type,
                                                        @RequestParam("remark") String remark,
                                                        @RequestParam("subType") String subType,
                                                        @RequestParam("creator") String creator,
                                                       HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<String> depotList = new ArrayList<>();
            if (!StringUtils.isEmpty(depotId)) {
                depotList.add(depotId);
            } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = depotService.findDepotByCurrentUser();
                for (Object obj : depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getString("id"));
                }
            }
            List<String> idList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = materialService.getListByParentId(categoryId);
            }
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            List<DepotHeadWithItem> list = depotHeadService.findPromotionMaterialDetail(beginTime, endTime, type, materialParam,
                    depotList, oId, number, remark, (currentPage - 1) * pageSize, pageSize,subType,creator,idList);
            Long total = depotHeadService.findPromotionMaterialDetailTotal(beginTime, endTime, type, materialParam,
                    depotList, oId, number, remark,subType,creator,idList);
            map.put("total", total);
            map.put("rows", list);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/findCheckMaterialDetail")
    @ApiOperation(value = "盘点单明细报表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadWithItem.class)
    })
    public BaseResponseInfo findCheckMaterialDetail(@RequestParam("currentPage") Integer currentPage,
                                                        @RequestParam("pageSize") Integer pageSize,
                                                        @RequestParam(value = "organId", required = false) String oId,
                                                        @RequestParam("number") String number,
                                                        @RequestParam("materialParam") String materialParam,
                                                        @RequestParam(value = "depotId", required = false) String depotId,
                                                        @RequestParam(value = "categoryId", required = false) String categoryId,
                                                        @RequestParam("beginTime") String beginTime,
                                                        @RequestParam("endTime") String endTime,
                                                        @RequestParam("type") String type,
                                                        @RequestParam("remark") String remark,
                                                        @RequestParam("subType") String subType,
                                                        @RequestParam("creator") String creator,
                                                        @RequestParam("materialId") String materialId,
                                                        HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<String> depotList = new ArrayList<>();
            if (!StringUtils.isEmpty(depotId)) {
                depotList.add(depotId);
            } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = depotService.findDepotByCurrentUser();
                for (Object obj : depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getString("id"));
                }
            }
            List<String> idList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = materialService.getListByParentId(categoryId);
            }
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            List<DepotHeadWithItem> list = depotHeadService.findCheckMaterialDetail(beginTime, endTime, type, materialParam,
                    depotList, oId, number, remark, (currentPage - 1) * pageSize, pageSize,subType,creator,materialId,idList);
            Long total = depotHeadService.findCheckMaterialDetailTotal(beginTime, endTime, type, materialParam,
                    depotList, oId, number, remark,subType,creator,materialId,idList);
            map.put("total", total);
            map.put("rows", list);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/findPackageMaterialDetail")
    @ApiOperation(value = "盘点单明细报表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadWithItem.class)
    })
    public BaseResponseInfo findPackageMaterialDetail(@RequestParam("currentPage") Integer currentPage,
                                                    @RequestParam("pageSize") Integer pageSize,
                                                    @RequestParam(value = "organId", required = false) String oId,
                                                    @RequestParam("number") String number,
                                                    @RequestParam("materialParam") String materialParam,
                                                    @RequestParam(value = "depotId", required = false) String depotId,
                                                    @RequestParam(value = "categoryId", required = false) String categoryId,
                                                    @RequestParam("beginTime") String beginTime,
                                                    @RequestParam("endTime") String endTime,
                                                    @RequestParam("type") String type,
                                                    @RequestParam("remark") String remark,
                                                    @RequestParam("subType") String subType,
                                                    @RequestParam("creator") String creator,
                                                    HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<String> depotList = new ArrayList<>();
            if (!StringUtils.isEmpty(depotId)) {
                depotList.add(depotId);
            } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = depotService.findDepotByCurrentUser();
                for (Object obj : depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getString("id"));
                }
            }
            List<String> idList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = materialService.getListByParentId(categoryId);
            }
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            List<DepotHeadWithItem> list = depotHeadService.findPackageMaterialDetail(beginTime, endTime, type, materialParam,
                    depotList, oId, number, remark, (currentPage - 1) * pageSize, pageSize,subType,creator,idList);
            Long total = depotHeadService.findPackageMaterialDetailTotal(beginTime, endTime, type, materialParam,
                    depotList, oId, number, remark,subType,creator,idList);
            map.put("total", total);
            map.put("rows", list);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/findSalesMarginList")
    @ApiOperation(value = "销售毛利表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = SalesMarginVo.class)
    })
    public BaseResponseInfo findSalesMarginList(@RequestParam("currentPage") Integer currentPage,
                                                    @RequestParam("pageSize") Integer pageSize,
                                                    @RequestParam(value = "marginType") Integer marginType,
                                                    @RequestParam(value = "organId", required = false) String oId,
                                                    @RequestParam(value = "materialName", required = false) String materialName,
                                                    @RequestParam("beginTime") String beginTime,
                                                    @RequestParam("endTime") String endTime,
                                                    @RequestParam(value = "creator", required = false) String creator,
                                                    HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<String> depotList = new ArrayList<>();
            //未选择仓库时默认为当前用户有权限的仓库
            JSONArray depotArr = depotService.findDepotByCurrentUser();
            for (Object obj : depotArr) {
                JSONObject object = JSONObject.parseObject(obj.toString());
                depotList.add(object.getString("id"));
            }
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            List<SalesMarginVo> list = depotHeadService.findSalesMarginList(beginTime, endTime,
                    depotList, oId,   (currentPage - 1) * pageSize, pageSize,creator,marginType,materialName);
            Long total = depotHeadService.findSalesMarginListTotal(beginTime, endTime,
                    depotList, oId, creator,marginType,materialName);
            map.put("total", total);
            map.put("rows", list);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }
    @GetMapping(value = "/findSalesMarginDetail")
    @ApiOperation(value = "销售毛利明细表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = SalesMarginDetailVo.class)
    })
    public BaseResponseInfo findSalesMarginDetail(@RequestParam("currentPage") Integer currentPage,
                                                @RequestParam("pageSize") Integer pageSize,
                                                @RequestParam(value = "marginType") Integer marginType,
                                                @RequestParam(value = "organId", required = false) String oId,
                                                @RequestParam(value = "materialName", required = false) String materialName,
                                                @RequestParam(value = "categoryId", required = false) String categoryId,
                                                @RequestParam("beginTime") String beginTime,
                                                @RequestParam("endTime") String endTime,
                                                @RequestParam(value = "creator", required = false) String creator,
                                                @RequestParam(value = "materialId", required = false) String materialId,
                                                HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<String> depotList = new ArrayList<>();
            //未选择仓库时默认为当前用户有权限的仓库
            JSONArray depotArr = depotService.findDepotByCurrentUser();
            for (Object obj : depotArr) {
                JSONObject object = JSONObject.parseObject(obj.toString());
                depotList.add(object.getString("id"));
            }
            List<String> idList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = materialService.getListByParentId(categoryId);
            }
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            List<SalesMarginDetailVo> list = depotHeadService.findSalesMarginDetail(beginTime, endTime,
                    depotList, oId,   (currentPage - 1) * pageSize, pageSize,creator,marginType,materialName,materialId,idList);
            Long total = depotHeadService.findSalesMarginDetailTotal(beginTime, endTime,
                    depotList, oId, creator,marginType,materialName,materialId,idList);
            map.put("total", total);
            map.put("rows", list);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/getTenantIdByDepotId")
    @ApiOperation(value = "针对报价单选择采购订单时，返回采购订单仓库的租户id")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = Depot.class)
    })
    public BaseResponseInfo getTenantIdByDepotId(@RequestParam("number") String number,
                                                     HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            Depot depot = depotHeadService.getTenantIdByDepotId(number);
            res.code = 200;
            res.data = depot;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/getDailySales")
    @ApiOperation(value = "每日销售报表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DailySales.class)
    })
    public BaseResponseInfo getDailySales(@RequestParam(value = Constants.SEARCH, required = false) String search,
                                              @RequestParam("currentPage") Integer currentPage,
                                              @RequestParam("pageSize") Integer pageSize,
                                                HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String tenantId = StringUtil.getInfo(search, "tenantId");
        try {
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            List<DailySales> list = depotHeadService.findDailySales(beginTime, endTime,(currentPage - 1) * pageSize, pageSize, tenantId);
            int total = depotHeadService.findDailySalesTotal(beginTime, endTime,tenantId);
            map.put("rows", list);
            map.put("creditPayment", depotHeadService.creditPayment(beginTime, endTime,tenantId));
//            map.put("totalCreditPayment", depotHeadService.totalCreditPayment(beginTime, endTime,tenantId));
            List<DailySales> list1 = depotHeadService.creditInvoices(beginTime, endTime, tenantId);
            map.put("creditInvoices", list1);
            map.put("total", total);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }
    @GetMapping(value = "/getDailySalesDetail")
    @ApiOperation(value = "每日职员销售")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DailySalesUserVo.class)
    })
    public BaseResponseInfo getDailySalesDetail(@RequestParam(value = Constants.SEARCH, required = false) String search,
                                                 @RequestParam("currentPage") Integer currentPage,
                                                 @RequestParam("pageSize") Integer pageSize,
                                          HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String tenantId = StringUtil.getInfo(search, "tenantId");
        if (StringUtil.isEmpty(tenantId)){
            res.code = 500;
            res.data = "租户id不能为空";
            return res;
        }
        try {
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            List<DailySalesUserVo> list = depotHeadService.getDailySalesDetail(beginTime, endTime,(currentPage - 1) * pageSize, pageSize, tenantId);
//            int total = depotHeadService.getDailySalesDetailTotal(beginTime, endTime, creator);
            map.put("rows", list);
//            map.put("total", total);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/getDailySummarySales")
    @ApiOperation(value = "按天汇总报表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DailySales.class)
    })
    public BaseResponseInfo getDailySummarySales(@RequestParam(value = Constants.SEARCH, required = false) String search,
                                          HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<String, Object>();
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        try {
            List<DailySummarySalesVo> list = depotHeadService.getDailySummarySales(beginTime, endTime);
            map.put("rows", list);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/salesOrderTracking")
    @ApiOperation(value = "销售订单追踪报表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = SalesOrderTracking.class)
    })
    public String salesOrderTracking(@RequestParam(value = Constants.SEARCH, required = false) String search,
                                        @RequestParam("currentPage") Integer currentPage,
                                        @RequestParam("pageSize") Integer pageSize,
                                        HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String organId = StringUtil.getInfo(search, "organId");
        String number = StringUtil.getInfo(search, "number");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String depotId = StringUtil.getInfo(search, "depotId");
        List<SalesOrderTracking> list = depotHeadService.salesOrderTracking(organId, number, beginTime, endTime,depotId,(currentPage - 1) * pageSize, pageSize);
        if (list != null) {
            objectMap.put("rows", list);
            objectMap.put("total", depotHeadService.salesOrderTracking(organId,  number, beginTime, endTime,depotId,null, null).size());
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("rows", new ArrayList<>());
            objectMap.put("total", 0);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }

    @GetMapping(value = "/findPosStockByMeId")
    @ApiOperation(value = "根据商品id查询库存数量")
    public BaseResponseInfo findPosStockByMeId(
            @RequestParam("mId") String mId,
            HttpServletRequest request) throws Exception{
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        try {
            List<String> materialIdList = StringUtil.strToStringList(mId);
            if(materialIdList!=null && materialIdList.size()>0) {
                Map<String,BigDecimal> currentStockMap = materialService.getCurrentStockMapByMaterialIdList(materialIdList,null);
                for (String materialId:materialIdList){
                    Map<String, Object> map = new HashMap<String, Object>();
                    BigDecimal stock = currentStockMap.get(materialId)!=null? currentStockMap.get(materialId): BigDecimal.ZERO;
                    map.put("id", materialId);
                    map.put("stock", stock);
                    data.add(map);
                }
            }
            res.code = 200;
            res.data = data;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/transferSummary")
    @ApiOperation(value = "调拨汇总")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TransferSummary.class)
    })
    public String transferSummary(@RequestParam(value = Constants.SEARCH, required = false) String search,
                                     @RequestParam("currentPage") Integer currentPage,
                                     @RequestParam("pageSize") Integer pageSize,
                                     HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String depotId = StringUtil.getInfo(search, "depotId");
        String categoryId = StringUtil.getInfo(search, "categoryId");
        String materialName = StringUtil.getInfo(search, "materialName");
        List<String> depotList = new ArrayList<>();
        if (!StringUtils.isEmpty(depotId)) {
            depotList.add(depotId);
        } else {
            //未选择仓库时默认为当前用户有权限的仓库
            JSONArray depotArr = depotService.findDepotByCurrentUser();
            for (Object obj : depotArr) {
                JSONObject object = JSONObject.parseObject(obj.toString());
                depotList.add(object.getString("id"));
            }
        }
        List<String> idList = new ArrayList<>();
        if(StringUtil.isNotEmpty(categoryId)){
            idList = materialService.getListByParentId(categoryId);
        }
        List<TransferSummary> list = depotHeadService.transferSummary(depotList, materialName, beginTime, endTime,(currentPage - 1) * pageSize, pageSize,idList);
        if (list != null) {
            objectMap.put("rows", list);
            objectMap.put("total", depotHeadService.transferSummary(depotList,  materialName, beginTime, endTime,null, null,idList).size());
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("rows", new ArrayList<>());
            objectMap.put("total", 0);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }

    @GetMapping(value = "/transferSummaryDetail")
    @ApiOperation(value = "调拨汇总明细")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = DepotHeadVo4InDetail.class)
    })
    public String transferSummaryDetail(@RequestParam(value = Constants.SEARCH, required = false) String search,
                                  @RequestParam("currentPage") Integer currentPage,
                                  @RequestParam("pageSize") Integer pageSize,
                                  HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String depotId = StringUtil.getInfo(search, "depotId");
        String materialId = StringUtil.getInfo(search, "materialId");
        List<String> depotList = new ArrayList<>();
        if (!StringUtils.isEmpty(depotId)) {
            depotList.add(depotId);
        } else {
            //未选择仓库时默认为当前用户有权限的仓库
            JSONArray depotArr = depotService.findDepotByCurrentUser();
            for (Object obj : depotArr) {
                JSONObject object = JSONObject.parseObject(obj.toString());
                depotList.add(object.getString("id"));
            }
        }
        List<DepotHeadVo4InDetail> list = depotHeadService.transferSummaryDetail(depotList, materialId, beginTime, endTime,(currentPage - 1) * pageSize, pageSize);
        if (list != null) {
            objectMap.put("rows", list);
            objectMap.put("total", depotHeadService.transferSummaryDetail(depotList,  materialId, beginTime, endTime,null, null).size());
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("rows", new ArrayList<>());
            objectMap.put("total", 0);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }

    @GetMapping(value = "/otherSummary")
    @ApiOperation(value = "其它出入库汇总")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TransferSummary.class)
    })
    public String otherSummary(@RequestParam(value = Constants.SEARCH, required = false) String search,
                                  @RequestParam("currentPage") Integer currentPage,
                                  @RequestParam("pageSize") Integer pageSize,
                                  HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String depotId = StringUtil.getInfo(search, "depotId");
        String categoryId = StringUtil.getInfo(search, "categoryId");
        String materialName = StringUtil.getInfo(search, "materialName");
        List<String> depotList = new ArrayList<>();
        if (!StringUtils.isEmpty(depotId)) {
            depotList.add(depotId);
        } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = depotService.findDepotByCurrentUser();
                for (Object obj : depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getString("id"));
                }
        }
        List<String> idList = new ArrayList<>();
        if(StringUtil.isNotEmpty(categoryId)){
            idList = materialService.getListByParentId(categoryId);
        }
        List<TransferSummary> list = depotHeadService.otherSummary(depotList, materialName, beginTime, endTime,(currentPage - 1) * pageSize, pageSize,idList);
        if (list != null) {
            objectMap.put("rows", list);
            objectMap.put("total", depotHeadService.otherSummary(depotList,  materialName, beginTime, endTime,null, null,idList).size());
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("rows", new ArrayList<>());
            objectMap.put("total", 0);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }
    @GetMapping(value = "/takeStockSummary")
    @ApiOperation(value = "盘点汇总")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TakeStockSummary.class)
    })
    public String takeStockSummary(@RequestParam(value = Constants.SEARCH, required = false) String search,
                               @RequestParam("currentPage") Integer currentPage,
                               @RequestParam("pageSize") Integer pageSize,
                               HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String depotId = StringUtil.getInfo(search, "depotId");
        String categoryId = StringUtil.getInfo(search, "categoryId");
        String materialName = StringUtil.getInfo(search, "materialName");
        List<String> depotList = new ArrayList<>();
        if (!StringUtils.isEmpty(depotId)) {
            depotList.add(depotId);
        } else {
            //未选择仓库时默认为当前用户有权限的仓库
            JSONArray depotArr = depotService.findDepotByCurrentUser();
            for (Object obj : depotArr) {
                JSONObject object = JSONObject.parseObject(obj.toString());
                depotList.add(object.getString("id"));
            }
        }
        List<String> idList = new ArrayList<>();
        if(StringUtil.isNotEmpty(categoryId)){
            idList = materialService.getListByParentId(categoryId);
        }
        List<TakeStockSummary> list = depotHeadService.takeStockSummary(depotList, materialName, beginTime, endTime,(currentPage - 1) * pageSize, pageSize,idList);
        if (list != null) {
            objectMap.put("rows", list);
            objectMap.put("total", depotHeadService.takeStockSummary(depotList,  materialName, beginTime, endTime,null, null,idList).size());
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("rows", new ArrayList<>());
            objectMap.put("total", 0);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }

    @GetMapping(value = "/findStockByMeIds")
    @ApiOperation(value = "根据商品id查询库存数量")
    public BaseResponseInfo findStockByMeIds(
            @RequestParam("depotId") String depotId,
            @RequestParam("mId") String mId,
            HttpServletRequest request) throws Exception{
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        try {
            List<String> materialIdList = StringUtil.strToStringList(mId);
            if(materialIdList!=null && materialIdList.size()>0) {
                Map<String,BigDecimal> currentStockMap = materialService.getCurrentStockMapByMaterialIdList(materialIdList,depotId);
                for (String materialId:materialIdList){
                    Map<String, Object> map = new HashMap<String, Object>();
                    BigDecimal stock = currentStockMap.get(materialId)!=null? currentStockMap.get(materialId): BigDecimal.ZERO;
                    map.put("id", materialId);
                    map.put("stock", stock);
                    data.add(map);
                }
            }
            res.code = 200;
            res.data = data;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/AllotList")
    @ApiOperation(value = "获取信息列表")
    public String AllotList(
                          @RequestParam(value = Constants.PAGE_SIZE, required = false) Integer pageSize,
                          @RequestParam(value = Constants.CURRENT_PAGE, required = false) Integer currentPage,
                          @RequestParam(value = Constants.SEARCH, required = false) String search,
                          HttpServletRequest request)throws Exception {
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> objectMap = new HashMap<String, Object>();
        String type = StringUtil.getInfo(search, "type");
        String subType = StringUtil.getInfo(search, "subType");
        String roleType = StringUtil.getInfo(search, "roleType");
        String status = StringUtil.getInfo(search, "status");
        String purchaseStatus = StringUtil.getInfo(search, "purchaseStatus");
        String number = StringUtil.getInfo(search, "number");
        String linkNumber = StringUtil.getInfo(search, "linkNumber");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String materialParam = StringUtil.getInfo(search, "materialParam");
        String organId =  StringUtil.getInfo(search, "organId");
        String creator =  StringUtil.getInfo(search, "creator");
        String depotId =  StringUtil.getInfo(search, "depotId");
        String accountId =  StringUtil.getInfo(search, "accountId");
        String remark = StringUtil.getInfo(search, "remark");
        String custom3 = StringUtil.getInfo(search, "custom3");
        String payStatus = StringUtil.getInfo(search, "payStatus");
        String freightStatus = StringUtil.getInfo(search, "freightStatus");
        String quotationStatus = StringUtil.getInfo(search, "quotationStatus");
        String custom4 = StringUtil.getInfo(search, "custom4");
        String color = StringUtil.getInfo(search, "color");
        String alwaysSelect = StringUtil.getInfo(search, "alwaysSelect");
        String itemType = StringUtil.getInfo(search, "itemType");
        String creditStatus = StringUtil.getInfo(search, "creditStatus");
        String depotStatus = StringUtil.getInfo(search, "depotStatus");
        List<DepotHeadVo4List> list = depotHeadService.selectAllot(type, subType, roleType, status, purchaseStatus, number, linkNumber, beginTime, endTime, materialParam,
                organId, creator, depotId, accountId, remark, custom3, (currentPage - 1) * pageSize, pageSize, payStatus,
                freightStatus, quotationStatus, custom4, color, alwaysSelect, itemType, creditStatus, depotStatus);

        if (list != null) {
            objectMap.put("total", depotHeadService.countDepotHeadAllot(type, subType, roleType, status, purchaseStatus, number, linkNumber, beginTime, endTime, materialParam,
                    organId, creator, depotId, accountId, remark,custom3,payStatus,
                    freightStatus,quotationStatus,custom4,color,alwaysSelect,itemType,creditStatus,depotStatus));
            objectMap.put("rows", list);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("total", BusinessConstants.DEFAULT_LIST_NULL_NUMBER);
            objectMap.put("rows", new ArrayList<Object>());
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }

    @GetMapping(value = "/findDepositWithPaymentById")
    @ApiOperation(value = "根据商品id查询库存数量")
    public BaseResponseInfo findDepositWithPaymentById(
            @RequestParam("headerId") String headerId,
            HttpServletRequest request) throws Exception{
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        try {
            DepotHeadVo4List dh = depotHeadService.selectByHeaderId(headerId);
            if ("厂家直发".equals(dh.getSubType())){
//                Map<String, BigDecimal> depositMap = accountHeadService.getDepositChangeByNumber(dh, "3");
                //订金
//                dh.setStraightDeposit(depositMap.get("changeAmount"));
                String straightDepositStr = accountHeadService.getDepositByLinkNumberWithCustom9(dh, "3");
                dh.setStraightDepositStr(straightDepositStr);
                //预收找零
//                dh.setDepositChange(depositMap.get("change"));
//                Map<String, BigDecimal> paymentMap  = accountHeadService.getDepositChangeByNumber(dh, "6");
                //实际收款
//                dh.setActualPayment(paymentMap.get("changeAmount"));
                //收款
                String paymentSalesOut = accountHeadService.getDepositByHeadLinkNumber(dh, "6","1");
                dh.setPaymentSalesOut(paymentSalesOut);
                //退款
                String paymentSalesOutRefunds = accountHeadService.getDepositByHeadLinkNumber(dh, "6","2");
                dh.setPaymentSalesOutRefunds(paymentSalesOutRefunds);
                //收款找零
//                dh.setPayChange(paymentMap.get("change"));
                //抵扣
//                dh.setDeduction(paymentMap.get("deduction"));
                //收款
//                dh.setReceivable(paymentMap.get("payment"));
            }else if ("销售订单".equals(dh.getSubType())){
//                Map<String, BigDecimal> depositMap = accountHeadService.getDepositChangeByNumber(dh, "4");
                //订金
//                dh.setStraightDeposit(depositMap.get("changeAmount"));
                String straightDepositStr = accountHeadService.getDepositByLinkNumberWithCustom9(dh, "4");
                dh.setStraightDepositStr(straightDepositStr);
                //预收找零
//                dh.setDepositChange(depositMap.get("change"));
//                Map<String, BigDecimal> paymentMap = accountHeadService.getDepositChangeByNumber(dh, "5");
                //实际收款
//                dh.setActualPayment(paymentMap.get("changeAmount"));
                String paymentSalesOut = accountHeadService.getDepositByHeadLinkNumber(dh, "5","1");
                dh.setPaymentSalesOut(paymentSalesOut);
                //退款
                String paymentSalesOutRefunds = accountHeadService.getDepositByHeadLinkNumber(dh, "5","2");
                dh.setPaymentSalesOutRefunds(paymentSalesOutRefunds);
                //收款找零
//                dh.setPayChange(paymentMap.get("change"));
                //抵扣
//                dh.setDeduction(paymentMap.get("deduction"));
                //收款
//                dh.setReceivable(paymentMap.get("payment"));
            }else  if ("销售".equals(dh.getSubType())){
                List<String> depositStr = accountHeadService.getCustom2ByBillId(dh, "5");
                List<String> strList=new ArrayList<>();
                if (depositStr!=null && depositStr.size()>0){
                    for (String deposit:depositStr){
                        List<String> list1 = StringUtil.strToStringList(deposit);
                        if (list1 !=null && list1.size()>0){
                            strList.addAll(list1);
                        }
                    }
                }
                if (strList.size() > 0){
                    String straightDepositStr = accountHeadService.getDepositByCustom2(strList);
                    dh.setStraightDepositStr(straightDepositStr);
                }
                String paymentSalesOut = accountHeadService.getPaymentByBillId(dh, "5");
                dh.setPaymentSalesOut(paymentSalesOut);

                List<String> idList = depotHeadService.getSalesOutByLinkNumber(dh.getNumber());
                if (idList != null && idList.size()>0){
                    String paymentSalesOutRefunds = accountHeadService.getPaymentByBillId(idList, "5");
                    dh.setPaymentSalesOutRefunds(paymentSalesOutRefunds);
                }
            }else if ("厂家到货".equals(dh.getSubType())){
                List<String> depositStr = accountHeadService.getCustom2ByBillId(dh, "6");
                List<String> strList=new ArrayList<>();
                if (depositStr!=null && depositStr.size()>0){
                    for (String deposit:depositStr){
                        List<String> list1 = StringUtil.strToStringList(deposit);
                        if (list1 !=null &&list1.size()>0){
                            strList.addAll(list1);
                        }
                    }
                }
                if (strList.size() > 0){
                    String straightDepositStr = accountHeadService.getDepositByCustom2(strList);
                    dh.setStraightDepositStr(straightDepositStr);
                }
                String paymentSalesOut = accountHeadService.getPaymentByBillId(dh, "6");
                dh.setPaymentSalesOut(paymentSalesOut);

                List<String> idList = depotHeadService.getSalesOutByLinkNumber(dh.getNumber());
                if (idList != null && idList.size()>0){
                    String paymentSalesOutRefunds = accountHeadService.getPaymentByBillId(idList, "6");
                    dh.setPaymentSalesOutRefunds(paymentSalesOutRefunds);
                }
            }else if ("直发销售退货".equals(dh.getSubType())){
                List<String> idList = new ArrayList<>();
                idList.add(dh.getId());
                if (idList.size() > 0){
                    String paymentSalesOutRefunds = accountHeadService.getPaymentByBillId(idList, "6");
                    dh.setPaymentSalesOutRefunds(paymentSalesOutRefunds);
                }
            }else if ("销售退货".equals(dh.getSubType())){
                List<String> idList = new ArrayList<>();
                idList.add(dh.getId());
                if (idList.size() > 0){
                    String paymentSalesOutRefunds = accountHeadService.getPaymentByBillId(idList, "5");
                    dh.setPaymentSalesOutRefunds(paymentSalesOutRefunds);
                }
            }
            res.code = 200;
            res.data = dh;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/findSalesTaxMoneyList")
    @ApiOperation(value = "销售税额")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = SalesTaxMoney.class)
    })
    public String findSalesTaxMoneyList(@RequestParam(value = Constants.SEARCH, required = false) String search,
                                   @RequestParam("currentPage") Integer currentPage,
                                   @RequestParam("pageSize") Integer pageSize,
                                   HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String depotId = StringUtil.getInfo(search, "depotId");
        List<String> depotList = new ArrayList<>();
        if (!StringUtils.isEmpty(depotId)) {
            depotList.add(depotId);
        } else {
            //未选择仓库时默认为当前用户有权限的仓库
            JSONArray depotArr = depotService.findDepotByCurrentUser();
            for (Object obj : depotArr) {
                JSONObject object = JSONObject.parseObject(obj.toString());
                depotList.add(object.getString("id"));
            }
        }

        List<SalesTaxMoney> list = depotHeadService.findSalesTaxMoneyList(depotList,  beginTime, endTime,(currentPage - 1) * pageSize, pageSize);
        if (list != null) {
            objectMap.put("rows", list);
            objectMap.put("total", depotHeadService.findSalesTaxMoneyList(depotList,   beginTime, endTime,null, null).size());
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("rows", new ArrayList<>());
            objectMap.put("total", 0);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }

}
